var new_bet = {}, chrome_msg = {};
var get_new_bet_loop, forbet;
var bet_re_msg = '', retry_times = 0;

function get_new_bet(){
	if (document.getElementById("btnLogout") == null){
		fatal_err_handle('188没有登录');
	}

    $.ajax({
        url: "http://115.28.130.157/view/get_new_autobet.php?"+Date.parse(new Date()),
        cache: false,
        type: "GET",
        dataType: "json"
    })
    .done(function(msg) {
        if(msg.error == 'succ'){
        	// 投注前停止抓去数据
        	window.clearInterval(get_new_bet_loop);
        	// 投注操作
        	forbet = msg;
            opt_bet();
        } else {
            new_bet.error = msg.error;
        }
    })
    .fail(function(jqXHR, textStatus) {
    	if (textStatus == 'parsererror'){
    		fatal_err_handle('115.28.130.157没有登录');
    	}
        new_bet.error = textStatus;
    });
}

// 致命错误处理
function fatal_err_handle(error_msg){
	window.clearInterval(get_new_bet_loop);
	chrome_msg.extensionerr = error_msg;
	chrome.runtime.sendMessage(chrome_msg);
}

// 开启按照间隔访问服务器
function roll_poll(){
	get_new_bet_loop = window.setInterval(get_new_bet, 5000);
}

roll_poll();


// 投注处理
function opt_bet(){
    forbet.betid = forbet.betid.replace(/o/, '');
    //window.location.href = 'http://sb.188bet.com/zh-cn/sports/1/in-play/full-time-asian-handicap-and-over-under?theme=black&q=&country=CN&currency=RMB';
    
    rm_all();
    setTimeout(choice_bet,  1000);
    setTimeout(on_refresh,  2000);
    setTimeout(set_money,   4000);
    setTimeout(on_bet,      5000);
    setTimeout(on_confirm,  6000);
    setTimeout(check_bet,   8000);

    chrome_msg.betre = 'succ';

    // 投注成功，告诉background.js
    chrome.runtime.sendMessage(chrome_msg);
}

// 全删除
function rm_all(){
    $(document.getElementById('sbkFrame').contentWindow.document.body).find("#BSRemoveAll").click();
}

// 选择投注对象
function choice_bet(){
    $(document.getElementById('sbkFrame').contentWindow.document.body).find("#o" + forbet.betid).click();
}

// 投注前刷新
function on_refresh(){
    //document.getElementById('btnRefreshRightPanel').click();
    document.getElementById("sbkFrame").contentDocument.getElementById('btnRefreshRightPanel').click();
}

// 投注金额
function set_money(){
    $(document.getElementById('sbkFrame').contentWindow.document.body).find("#stake_" + forbet.betid).val(forbet.betmoney);
    
	var _bet_money_input_obj = document.getElementById("sbkFrame").contentDocument.getElementById("stake_" + forbet.betid);
    var evObj = document.createEvent('KeyboardEvent');
    evObj.initEvent('keyup', true, false);
    _bet_money_input_obj.dispatchEvent(evObj);
}

// 投注
function on_bet(){
    document.getElementById("sbkFrame").contentDocument.getElementById('btnPlaceBet_BS').click();
}

// 投注确定
function on_confirm(){
    document.getElementById("sbkFrame").contentDocument.getElementById('btnConfirm_BS').click();
}

//检查投注结果
function check_bet(){
	var info_succ_obj = document.getElementById("sbkFrame").contentDocument.getElementById('bsGenneralMeg');
	
	if (info_succ_obj != null && info_succ_obj.className == 'info success'){
		// 投注成功
		bet_re_msg = info_succ_obj.getElementsByTagName('span')[1].innerHTML;
		after_bet();
		roll_poll();
		retry_times = 0;
	}else{
		// 投注失败
		bet_re_msg = document.getElementById("sbkFrame").contentDocument.getElementById('notice').innerHTML;
		// 失败重投
		if (retry_times ++ < 3){
			opt_bet();
		}else{
			// 超过重试次数不再重试
			retry_times = 0;
			roll_poll();
		}
	}
}

//投注完成后确定
function after_bet(){
	document.getElementById("sbkFrame").contentDocument.getElementById('btnOk_BS').click();
}


// ----- 跳转到 http://www.188bet.com/zh-cn/sports/1/in-play/full-time-asian-handicap-and-over-under -----
function skip_to_inplay(){
	var inplay_url = 'http://www.188bet.com/zh-cn/sports/1/in-play/full-time-asian-handicap-and-over-under';
	var current_url = window.location.href;
	if (current_url != inplay_url){
		window.location.href = inplay_url;
	}
}
window.setInterval(skip_to_inplay, 50 * 60 * 1000);

